import { routesConfig } from "@/libs/router/routes"
import { useTitle } from "@reactuses/core"
import React from "react"
import { Link } from "react-router-dom"

interface RouteEntry {
  path: string
  id?: string
  fullPath: string
  hasChildren: boolean
  isIndex: boolean
}

function getAllRoutePaths(
  routes: any[],
  parentPath: string = ""
): RouteEntry[] {
  let paths: RouteEntry[] = []

  routes.forEach((route) => {
    const currentPath = route.path || ""
    const fullPath = `${parentPath}/${currentPath}`.replace(/\/+/g, "/")

    const isRenderable = route.element && route.path !== "*"

    if (
      isRenderable ||
      route.children?.some((child: any) => child.index || child.path)
    ) {
      paths.push({
        path: currentPath,
        id: route.id,
        fullPath: fullPath === "/" && route.path === "" ? "/" : fullPath,
        hasChildren: !!route.children,
        isIndex: !!route.index,
      })
    }

    if (route.children) {
      paths = paths.concat(getAllRoutePaths(route.children, fullPath))
    }
  })

  return paths
}

const RouteDebuggerPage: React.FC<{ onClose?: () => void }> = ({ onClose }) => {
  useTitle("路由调试器 - 开发工具")
  const allRoutes = getAllRoutePaths(routesConfig)

  return (
    <div className="min-h-screen flex justify-center items-center p-6 font-sans text-gray-800">
      <div className="max-w-4xl mx-auto bg-white rounded-xl shadow-lg p-8 sm:p-10 space-y-8">
        <h1 className="text-4xl font-extrabold text-indigo-700 border-b-4 border-indigo-500 pb-4 mb-6">
          🚀 路由调试器
        </h1>

        <p className="text-lg text-gray-700 mb-6">
          此页面列出了应用程序中定义的所有可访问路由。点击链接可以快速导航到相应页面。
        </p>

        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {allRoutes.length > 0 ? (
            allRoutes.map((route, idx) => (
              <Link
                key={idx}
                to={route.fullPath}
                onClick={() => onClose?.()}
                className="
                  flex flex-col items-start
                  p-5 bg-blue-50 border border-blue-200 rounded-lg shadow-md
                  hover:bg-blue-100 hover:shadow-lg
                  transition-all duration-200 ease-in-out group
                "
              >
                <div className="text-indigo-600 font-semibold text-sm mb-1 group-hover:text-indigo-800">
                  ID: {route.id || "N/A"}
                </div>
                <div className="text-lg font-bold text-gray-800 group-hover:text-gray-900">
                  {route.fullPath === "/" ? "首页" : route.fullPath}
                </div>
                {route.isIndex && (
                  <span className="mt-1 px-2 py-0.5 bg-green-200 text-green-800 text-xs font-medium rounded-full">
                    默认子路由
                  </span>
                )}
                {route.hasChildren && (
                  <span className="mt-1 px-2 py-0.5 bg-purple-200 text-purple-800 text-xs font-medium rounded-full">
                    有子路由
                  </span>
                )}
              </Link>
            ))
          ) : (
            <p className="col-span-full text-center text-gray-600 text-lg">
              没有找到可渲染的路由信息。
            </p>
          )}
        </div>

        <div className="mt-10 pt-6 border-t-2 border-gray-200 text-gray-600 text-sm">
          <h3 className="font-semibold mb-2 text-gray-700">注意事项：</h3>
          <ul className="list-disc list-inside space-y-1">
            <li>
              此工具仅显示通过 `routesConfig` 静态定义的路由。动态路由不会显示。
            </li>
            <li>`*` (通配符) 路由不会以链接形式列出。</li>
            <li>确保你的 `RouterProvider` 正确配置在 `App.tsx`。</li>
          </ul>
        </div>
      </div>
    </div>
  )
}

export default RouteDebuggerPage
